package com.hjb.lock.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * redis锁服务操作
 */
class RedisLockInternals {
	
	private static final Logger logger = LoggerFactory.getLogger(RedisLockInternals.class);
	
    private JedisPool jedisPool;
    
    private JedisCluster jedisCluster;

    /**
     * 重试等待时间
     */
    private int retryAwait=300;

    /**
     * 实例redis客服端工具，通过获取bean时判断是单机还是集群配置
     */
    RedisLockInternals(Object jedisLock) {
    	if(jedisLock instanceof JedisPool){
    		this.jedisPool = (JedisPool) jedisLock;
    	}else if(jedisLock instanceof JedisCluster){
    		this.jedisCluster = (JedisCluster) jedisLock;
    	}
    }

    /**
     * 加入锁
     * @param lockId 业务锁ID
     * @param time 业务执行时间
     * @param unit 锁规则配置
     * @return String
     */
    String tryRedisLock(String lockId,long timeout, TimeUnit unit) {
        final long startMillis = System.currentTimeMillis();
        final Long millisToWait = (unit != null) ? unit.toMillis(timeout) : null;
        String lockValue=null;
        while (lockValue==null){
            lockValue=createRedisKey(lockId,timeout);
            if(lockValue!=null){
                break;
            }
            if(System.currentTimeMillis()-startMillis-retryAwait>millisToWait){
                break;
            }
            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(retryAwait));
        }
        return lockValue;
    }

    /**
     * 通过eval命令创建redis锁
     * @param lockId 业务锁ID
     * @return String
     */
    private String createRedisKey(String lockId,Long timeout) {
        String value=lockId+randomId(1);
        if(jedisPool != null){
            Jedis jedis = null;
            try {
                jedis = jedisPool.getResource();
                Long result = jedis.setnx(lockId,value);
                if(result == 1){
                    jedis.pexpire(lockId,timeout);
                    return value;
                }
            }finally {
                if(jedis!=null) jedis.close();
            }
        }
        if(jedisCluster != null){
            try {
                Long result = jedisCluster.setnx(lockId,value);
                if(result == 1){
                    jedisCluster.pexpire(lockId,timeout);
                    return value;
                }
            }finally {
                if(jedisCluster!=null){
                    try {
                        jedisCluster.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        }
        return null;
    }

    /**
     * 销毁锁
     * @param key
     * @param value
     */
    void unlockRedisLock(String key,String value) {
        if(jedisPool != null){
            Jedis jedis = null;
            try {
                jedis = jedisPool.getResource();
                if(value.equals(jedis.get(key))){
                    jedis.del(key);
                }
            }finally {
                if(jedis!=null) jedis.close();
            }
        }
        if(jedisCluster != null){
            try {
                if(value.equals(jedisCluster.get(key))){
                    jedisCluster.del(key);
                }
            }finally {
                if(jedisCluster!=null){
                    try {
                        jedisCluster.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        }
    }

    private final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
            'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
            'Z'};

    private String randomId(int size) {
        char[] cs = new char[size];
        for (int i = 0; i < cs.length; i++) {
            cs[i] = digits[ThreadLocalRandom.current().nextInt(digits.length)];
        }
        return new String(cs);
    }
}
